<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserPointsLog extends Model
{
    const  REASON_TYPE_SIGN = 1;//签到
    const  REASON_TYPE_DB2POINTS = 2;//D币转积分
    const  REASON_TYPE_RESOURCE_DOWNLOADED = 3;//资源被下载
    const  REASON_TYPE_DOWNLOAD_RESOURCE = 4;//下载资源
    const  REASON_TYPE_MANMODIFIED = 5;//人为修改
    const REASON_TYPE_VIP_ADD = 6; //vip充值
    //白名单
    //protected $fillable = ['user_id','type','points','remain_points','reason_type'];
    //最新一条是最后的剩余积分数
    public static function getLatestUPLog($user_id)
    {
        $user_points_list = UserPointsLog::where('user_id', $user_id)
            ->orderBy('updated_at', 'DESC')
            ->take(1)
            ->get();//colloection
        if (!count($user_points_list)) {
            return null;
        }
        return $user_points_list[0];
    }

    public static function pointStatistic($user_id)
    {
        $cur_point_item = UserPointsLog::getLatestUPLog($user_id);
        $res['remain_points'] = 0;
        $res['add_points'] = 0;
        $res['minus_points'] = 0;
        //当前积分数
        if (!empty($cur_point_item) && !empty($cur_point_item['remain_points'])) {
            $res['remain_points'] = $cur_point_item['remain_points'];
        }
        //增加的积分数
        $user_points_add = UserPointsLog::where('user_id', $user_id)
            ->where('type', 1)
            ->sum('points');
        if (!empty($user_points_add)) {
            $res['add_points'] = $user_points_add;
        }
        //消耗的积分数
        $user_points_minus = UserPointsLog::where('user_id', $user_id)
            ->where('type', 2)
            ->sum('points');
        if (!empty($user_points_minus)) {
            $res['minus_points'] = $user_points_minus;
        }

        return $res;

    }

    public static function userPointList($user_id, $limit = 20)
    {
        //取最前面的10条
        $user_point_list = UserPointsLog::where('user_id', $user_id)
            ->orderBy('updated_at', 'DESC')
            ->paginate($limit);
        return $user_point_list;
    }

    /*
     * 关联模型
     */
    public function user()
    {
        return $this->belongsTo('App\\Models\\User');
    }

}
